package com.zhanghu.backendZray.utils.weather;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhanghu.backendZray.pojo.dto.location.LocationAPIDTO;
import com.zhanghu.backendZray.pojo.dto.weather.SeniverseAPIResDTO;
import com.zhanghu.backendZray.pojo.dto.weather.WeatherAPIDetailDTO;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZhangDong
 * @date 2024/9/11 14:48
 */
@Slf4j
public class WeatherUtil {

    private static final String WEATHER_SDK_URL = "https://api.seniverse.com/v3/weather/daily.json";
    private static final String LOCATION_SDK_URL = "https://api.seniverse.com/v3/location/search.json";

    /**
     * 心知天气
     * 获取最近三天的天气
     *
     * @param location 这个免费的api 只支持地级市，输入 泰州 or 泰州市 都可以
     */
    public static WeatherAPIDetailDTO getRecent3DaysWeather(String apiKey, String location) {
        String url = String.format("%s?key=%s&location=%s&language=zh-Hans&unit=c&start=0&days=3", WEATHER_SDK_URL, apiKey, location);
        // error eg 输入“吴中” : {"status":"You don't have access to data of this city.","status_code":"AP010006"}
        // 输入“苏州吴中”： {"status":"The location can not be found.","status_code":"AP010010"}
        String response = HttpRequest.get(url).execute().body();
        log.info("心知天气, 获取最近三天的天气, location:{}, response:{}", location, response);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            SeniverseAPIResDTO<WeatherAPIDetailDTO> seniverseAPIResDTO = objectMapper.readValue(response, SeniverseAPIResDTO.class);
            return JSON.parseObject(JSON.toJSONString(seniverseAPIResDTO.getResults().get(0)), WeatherAPIDetailDTO.class);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 心知天气
     * 根据经纬度查询城市
     *
     * @return
     */
    public static SeniverseAPIResDTO<LocationAPIDTO> searchLocation(String apiKey, String location) {
        String url = String.format("%s?key=%s&q=%s", LOCATION_SDK_URL, apiKey, location);
        String response = HttpRequest.get(url).execute().body();
        log.info("心知天气, 根据经纬度查询城市, location:{}, response:{}", location, response);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(response, SeniverseAPIResDTO.class);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        WeatherAPIDetailDTO dto = getRecent3DaysWeather("SNqdEFmvr9yg-ob4e", "苏州");
        System.err.println(JSON.toJSONString(dto));
    }
}
